#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>

// 回调函数，用于处理服务器响应数据
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t totalSize = size * nmemb;
    strncat(userp, contents, totalSize);
    return totalSize;
}

// 打印解析的 JSON 数据
void print_parsed_data(const char *response, size_t size) {
    // 解析 JSON 响应
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (json == NULL) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    // 获取 "data" 对象
    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    

    // 获取并打印 "region" 字符串
    cJSON *region = cJSON_GetObjectItemCaseSensitive(data, "region");
    if (cJSON_IsString(region) && (region->valuestring != NULL)) {
        printf("Region: %s\n", region->valuestring);
    } else {
        fprintf(stderr, "JSON 格式错误: 找不到 'region' 字符串\n");
    }

    // 获取并打印 "weatherData" 对象
    cJSON *weatherData = cJSON_GetObjectItemCaseSensitive(data, "weatherData");
    if (cJSON_IsObject(weatherData)) {
        cJSON *temperature = cJSON_GetObjectItemCaseSensitive(weatherData, "temperature");
        if (cJSON_IsNumber(temperature)) {
            printf("Temperature: %d\n", temperature->valueint);
        }
        cJSON *weather = cJSON_GetObjectItemCaseSensitive(weatherData, "weather");
        if (cJSON_IsString(weather) && (weather->valuestring != NULL)) {
            printf("Weather: %s\n", weather->valuestring);
        }
        // 其他天气数据可以按类似方式提取和打印
    } else {
        fprintf(stderr, "JSON 格式错误: 找不到 'weatherData' 对象\n");
    }

   

    // 释放 JSON 对象
    cJSON_Delete(json);
}

int main(void) {
    CURL *client;
    CURLcode err;
    char buffer[8192] = {0}; // 用于存储响应数据

    // 初始化 CURL
    curl_global_init(CURL_GLOBAL_ALL);
    client = curl_easy_init();

    // 设置 CURL 选项
    curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/info");
    curl_easy_setopt(client, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(client, CURLOPT_WRITEDATA, buffer);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "X-User-Token: o9M10gtneoIxRLk5UO13fUG7guYxnS7h"); // 替换 YOUR_API_KEY 为你的 API Key
    curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);

    // 执行 CURL 请求
    err = curl_easy_perform(client);

    if (err != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(err));
    } else {
        // 解析并打印 JSON 数据
        print_parsed_data(buffer, strlen(buffer));
    }

    // 清理资源
    curl_slist_free_all(headers);
    curl_easy_cleanup(client);
    curl_global_cleanup();

    return 0;
}
